<template>
  <view>
    <image src="../../image/bg.png" class="bgImg" />
    <view class="top-title" :style="{height:customBar+'px',paddingTop:statusBar+'px'}">
      <view class="top-title-back" @tap="goBack">
        <image src="../../image/back.png" />
      </view>
      <text class="top-title-t1">储值卡详情</text>
    </view>
    <view class="card-title">
      <text class="card-title-t1">储值卡</text>
    </view>
    <view class="card">
      <image :src="imgUrl+'/cardbg.png'" class="img" />
      <view class="card-right">
        <view class="rt-p1">
          <image :src="imgUrl+'/car.png'" class="rt-img1" />&nbsp;
          <text>{{carNo||'暂无车牌'}}</text>
        </view>
        <view @tap="dialogPlate=true" class="rt-btn" v-if="plateList.length>0">更换车牌</view>
        <view @tap="addPlate=true" class="rt-btn" v-else>添加车牌</view>
        <view class="rt-p2">{{carInfos.parkName||"暂无车场数据"}}</view>
      </view>
    </view>
    <view class="title">选择储值卡金额</view>
    <view class="money">
      <view
        v-for="(item,index) in navTab"
        :key="index"
        @tap="currentTab(item,index)"
        :class="active==index ? 'active' : ''"
      >
        <text class="p1" v-if="item.pmr_original_price">满{{item.pmr_original_price}}送{{item.discount}}</text>
        <text class="p1" v-else>{{item.label}}</text>
      </view>
    </view>
    <view class="title" v-if="navTab[0].label" style="margin-bottom:0">自定义金额</view>
    <view class="box1" v-if="navTab[0].label">
      <input
        placeholder="请输入金额"
        v-model="value"
        type="number" confirm-type='done'
        class="inp1"
        @blur="bindKeyInput(value)"
      />
    </view>
    <view class="info">支付前请确认车牌号准确!</view>
    <view style="padding-bottom:50px">
      <view class="btn" @tap="goRecharge">支付{{amount}}元</view>
    </view>
    
    <!--车牌列表-->
    <view class="open-dialog" v-if="dialogPlate">
      <image :src="imgUrl+'/close.png'" class="open-closed" @tap="dialogPlate=false" />
      <view class="open-ul">
        <view
          class="open-item"
          v-for="(item,index) in plateList"
          :key="index"
          @tap="handlePlate(item,index)"
        >
          <text class="open-p1">{{item.carNo}}</text>
          <image :src="imgUrl+'/selected.png'" class="open-img" v-if="currentPlate==index" />
        </view>
      </view>
      <view class="btn-box">
        <view class="btn1" @tap="openPlate" style="width:44%">添加车牌</view>
        <view class="btn2" @tap="sumitSurePlate" style="width:44%">确认</view>
      </view>
    </view>
    <!--车牌添加-->
    <view class="open-dialog dialog2" v-if="addPlate">
      <view class="title" style="padding-left:15px">新增车牌</view>
      <keyBoard :carNum="carNum" :showKeyboard="true" @onOk="onOk" @onCancel="onCancel" />
      <view class="btn-box">
        <view class="btn1" @tap="plateReset">取消</view>
        <view class="btn2" @tap="sumitPlate">确认</view>
      </view>
    </view>
    <!--授权手机号-->
    <view v-if="!hasPhone" class="open-dialog">
      <image src="../../image/close.png" class="panel-box-close" @tap="hasPhone=true" />
      <view class="title text-center">提示</view>
      <view class="info">尚未获取手机号，无法购买储值卡</view>
      <button
        openType="getPhoneNumber"
        @GetPhoneNumber="onGetPhoneNumber"
        class="panel-box-btn"
        style="height:100rpx"
      >获取手机号</button>
    </view>
    <view class="panel-bg" v-if="dialogPlate||addPlate||!hasPhone||isAgree"></view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./storedRecharge.less";
import keyBoard from "../../components/keyBoard/keyBoard.vue";
import { setGlobalData, getGlobalData } from "../../globalData.js";
import bulterApi from "@souche2014/bulter-api";
import { request } from "../../util/axios.js";
const api = bulterApi({ partner: "IOParking" });
// pages/card/storeRecharge.js
var common = require("../../common.js");
export default {
  name: "storedRecharge",
  data() {
    return {
      imgUrl: process.env.IOParking.IMG_URL,
      mobile: "",
      openId: "",
      navTab: [ {
                label: "100元",
                value: 100,
                index: 0
              },
              {
                label: "200元",
                value: 200,
                index: 1
              },
              {
                label: "500元",
                value: 500,
                index: 2
              }],
      active: 0, //默认一个月
      dialogPlate: false, //车牌号
      isAgree: false,
      agreeChecked: true,
      hasPhone: true,
      showKeyboard: true,
      carNum: [],
      showKeyboard: false,
      addPlate: false,
      plateList: [],
      currentPlate: 0,
      apiBaseUrl: process.env.IOParking.API_HOST, //请求头
      id: 0,
      chargId:0,
      carInfos: {},
      months: 0,
      amount: 0,
      feeTemplate: {
        date_type_switch: "",
        date_type_name: "",
        available_period_switch: "",
        free_start_time: "",
        free_end_time: ""
      },
      beginTime: "", //月租卡续费开始时间
      endTime: "", //月租卡续费结束时间
      statusBar: 0, //状态栏高度
      customBar: 0, //胶囊按钮高度
      value: "",
      carNo: "", //确认车牌号
      plate: "" //更换时点击的车牌号
    };
  },
  components: { keyBoard },
  mounted() {
    Taro.getSystemInfo({
      success: res => {
        this.statusBar = res.statusBarHeight; //状态栏高度
        let custom = Taro.getMenuButtonBoundingClientRect(); //菜单按钮
        this.customBar = custom.height + 8;
        console.log(this.statusBar, this.customBar);
      }
    });
  },
  onLoad: function(options) {
    this.id = options.id;
    this.initData();
    if (!getGlobalData("openId")) {
      this.wx_login();
    } else {
      this.getPlateList();
    }
  },
  onShareAppMessage: function() {
		wx.showShareMenu({
	      withShareTicket: true,
	      menus: ['shareAppMessage', 'shareTimeline']
	    })
	},
	//用户点击右上角分享朋友圈
	onShareTimeline: function () {
		return {
	      title: '储值卡',
	      query: {
          feeId: this.id
	      },
	    }
	},
  methods: {
    wx_login() {
      var that = this;
      api
        .getUserInfo({
          scope: "all"
        })
        .then(resp => {
          if (resp.success) {
            console.log("authCode is：", resp.data);
            if (resp.data == "mock") {
              setGlobalData("openId", "oRPxj5ZrsZGRuxTa-UrzEBeLuv-s");
              //setGlobalData("mobile", "17761643218");
              that.getPlateList();
              return;
            }
            that.getInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
    getInfos(authCode) {
      var that = this;
      Taro.request({
        url: this.apiBaseUrl + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "GET",
        success(res) {
          console.log("获取用户信息：", res.data);
          if (res.data.isSuccess) {
            var userOpenId = res.data.data.openId;
            setGlobalData("openId", userOpenId);
            setGlobalData("mobile", res.data.data.phoneNum);
            that.getPlateList();
            api.bury("userAuthorizationNum", {
              parkName: "",
              parkId: "",
              time: new Date().valueOf(),
              mobile: getGlobalData("mobile") ? getGlobalData("mobile") : ""
            });
          }
        }
      });
    },
    onGetPhoneNumber({ detail }) {
      const { encryptedData, iv } = detail;
      console.log("phone打印:" + JSON.stringify(detail));
      if (encryptedData && iv) {
        this.authPhone(encryptedData, iv);
        this.hasPhone = true;
        Taro.showLoading({
          title: "授权中，请稍后",
          mask: true
        });
      }
    },
    authPhone(encryptedData, iv) {
      api
        .register({
          encryptedData: encryptedData,
          iv: iv,
          scope: "all"
        })
        .then(resp => {
          Taro.hideLoading();
          if (resp.success) {
            console.log("用户注册 ", resp.data);
            if (resp.data == "mock") {
              setGlobalData("mobile", "17761643218");
              this.mobile = getGlobalData("mobile")
                ? getGlobalData("mobile")
                : "";
              return;
            }
            this.getInfos(resp.data);
          } else {
            console.log("err is ", resp.msg, "err code is ", resp.code);
          }
        })
        .catch(e => {
          console.log(e);
        });
    },
    initData() {
      var that = this;
      var base = this.apiBaseUrl;
      let params = {
        feeId: that.id
      };
      request("/onlinepayment/getparkfeeinfo", params).then(res => {
        that.carInfos = res.data.park;
        that.chargId = res.data.chargId;
        that.getFeediscountinfo();
      });
    },
    getFeediscountinfo() {
      var that = this;
      var base = this.apiBaseUrl;
      let params = {
        feeId: +that.id
      };
       Taro.showLoading({
        title: "加载中",
        mask: true
      });
      Taro.request({
        url: base + "/onlinepayment/feediscountinfo",
        data: params,
        method: "POST",
        success(res) {
          Taro.hideLoading();
          if (res.data.isSuccess) {
            that.navTab = JSON.parse(res.data.data.chargStandard);
            that.amount = that.navTab[0].pmr_original_price;
          } else {
             that.amount = 100
          }
        }
      });
    },
    //历史车牌
    getPlateList() {
      var that = this;
      request("/parkingpayment/getcarnorecord").then(res => {
        that.plateList = res.data;
        if (that.plateList[0]) that.carNo = that.plateList[0].carNo;
      });
    },
    goRecharge(e) {
      var that = this;
      if (getGlobalData("mobile") == "" || !getGlobalData("mobile")) {
        that.hasPhone = false;
        return;
      }
      if (that.carNo.length < 7) {
        Taro.showToast({
          title: "请添加车牌号",
          icon: "error",
          duration: 1000,
          mask: true
        });
        return;
      }
      wx.showModal({
        title: "提示",
        content:
          "亲爱的车主，请您确定购买的储值卡绑定的车牌" +
          that.carNo +
          "是否有误，确认后绑定车牌无法修改！",
        success(res) {
          if (res.confirm) {
            //确认
            let params = {
              amount: +that.amount,
              chargId: +that.id,
              parkId: that.carInfos.id,
              carno: that.carNo,
              openId: getGlobalData("openId")
            };
            request("/onlinepayment/addstorecard", params).then(res => {
              that.wxPay(res.data.wxPayOrderParams);
            });
          } else if (res.cancel) {
          }
        }
      });
    },
    wxPay(obj, orderId) {
      //微信支付
      var that = this;
      Taro.requestPayment({
        timeStamp: obj.timeStamp,
        nonceStr: obj.nonceStr,
        package: obj.package,
        signType: obj.signType,
        paySign: obj.paySign,
        success(res) {
          Taro.navigateTo({
            url: "../openCard/paySuccess"
          });
        },
        fail(res) {
          console.log(res);
        }
      });
    },
    goBack() {
      Taro.reLaunch({
            url: "../openCard/maps?chargType=2"
          });
    },
    currentTab(item, index) {
      //充值金额切换
      var that = this;
      if (that.currentTab == index) {
        return;
      }
      that.active = index;
      that.value=''
      if (item.pmr_original_price) {
        that.amount = that.plus(item.pmr_original_price,item.discount);
        // that.discountAmount = item.discount;
        // that.payAmount = item.pmr_original_price;
      } else {
        that.amount = item.value;
        // that.discountAmount = 0;
        // that.payAmount = item.value;
      }
    },
    handlePlate: function(item, index) {
      if (this.currentPlate == index) {
        return;
      }
      this.currentPlate = index;
      this.plate = item.carNo;
    },
    sumitSurePlate() {
      this.carNo = this.plate;
      this.dialogPlate = false;
    },
    //添加车牌号，弹出
    openPlate: function() {
      this.dialogPlate = false;
      this.addPlate = true;
    },
    inputCarNum() {
      this.showKeyboard = true;
    },

    onOk(e) {
      this.plate = e;
    },
    onCancel() {
      this.dialogPlate = false;
      this.addPlate = false;
    },
    plateReset() {
      this.addPlate = false;
      // this.carNum=['豫','','','','','','']
    },
    sumitPlate() {
      if (this.plate.length > 6) {
        this.plateList.unshift({ carNo: this.plate });
        this.addPlate = false;
        this.dialogPlate = true;
        this.plate = this.plateList[0].carNo;
      } else {
        Taro.showToast({
          title: "请录入完整车牌",
          icon: "error",
          duration: 1000,
          mask: true
        });
      }
    },
    handleAgreeChecked() {
      this.agreeChecked = !this.agreeChecked;
    },
    bindKeyInput(e) {
      console.log(e);
      var re = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
      if (e > 0) {
        if (re.test(e)) {
          this.value = e;
          this.amount = e;
          this.active = -1;
        } else {
          Taro.showToast({
            title: "金额不正确",
            icon: "error",
            duration: 1000,
            mask: true
          });
          this.amount = 100;
          this.value = "";
          this.active = 0;
        }
      } else {
        this.amount = 100;
        this.value = "";
        this.active = 0;
      }
    },
  }
};
</script>
